package com.bw.controller;

import com.bw.entity.Result;
import com.bw.entity.User;
import com.bw.entity.Word;
import com.bw.service.WordService;
import com.bw.util.Aes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("word")
public class WordController {

    @Autowired
    private WordService wordService;

    /**
     * 新增单词
     * @param word
     * @param request
     * @return
     */
    @RequestMapping("addWord")
    @ResponseBody
    public Result addWord(@RequestBody Word word, HttpServletRequest request) {
        if(word == null || word.getWord()==null ||word.getWord().trim().equals("") || word.getDescription()==null||word.getWordProperty()==null) {
            throw new NullPointerException("word为空");
        }
        try {
            String s = Aes.aesJDecrypt(word.getWord());
            word.setWord(s);
            String regEx = "[A-Za-z]+";
            Pattern pattern = Pattern.compile(regEx);
            Matcher matcher = pattern.matcher(word.getWord());
            boolean rs = matcher.matches();
            if(rs==false){
                throw new NullPointerException("请输入正确的单词");
            }
            wordService.addWord(word);
            Integer wid = word.getId();
            User user = (User) request.getSession().getAttribute("user");
            Integer sid = user.getId();
            Map map = new HashMap();
            map.put("wid", wid);
            map.put("sid", sid);
            wordService.addMid(map);
            return new Result(true, "增加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "增加失败");
        }
    }

    /**
     * 检查单词是否存在
     * @param word
     * @return
     */
    @RequestMapping("checkWord")
    @ResponseBody
    public boolean checkWord(String word) {
        if(word == null || "".equals(word)) {
            throw new NullPointerException("word为空");
        }
        Word w = wordService.checkWord(word);
        System.out.println(w);
        if(w == null) { return true;}
        else { return false;}
    }
}
